package city.spring.modules.personnel.service.impl;

import city.spring.modules.personnel.entity.EmployeeNoticeEntity;
import city.spring.modules.personnel.repository.EmployeeNoticeRepository;
import city.spring.modules.personnel.service.EmployeeNoticeService;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Service：通知公告
 *
 * @author Panxm
 * @date 2020-04-10 11:12:16
 */
@CacheConfig(cacheNames = {EmployeeNoticeServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class EmployeeNoticeServiceImpl extends ServiceImpl<EmployeeNoticeRepository, EmployeeNoticeEntity> implements EmployeeNoticeService {
    private final UserService userService;

    public EmployeeNoticeServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void saveEmployeeNotice(EmployeeNoticeEntity entity, @NonNull Principal user) {
        /**
         * 获取当前时间，格式化为yyyyMMddmmss，转为string类型，拼接INFO+yyyyMMddmmss作为通告编号
         */
        String nowTimestr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String numcode = "INFO" + nowTimestr;
        entity.setNoticeNum(numcode);
        entity.setCreatTime(new Date());

        // 通知的发布人：当前用户id、部门
        UserEntity userEntity = userService.getUserByIdOrAccount(user.getName());
        entity.setPublisher(userEntity.getId());
        entity.setDept(userEntity.getOrgId());
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }


    @Override
    public void updateEmployeeNotice(EmployeeNoticeEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteEmployeeNotice(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteEmployeeNotice(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }
}